# 测试实例暂为使用

import logging
from flask import Flask, has_request_context, request, jsonify
from loguru import logger

class FlaskLogger:
    def __init__(self, app=None):
        self.app = app
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        # 替换 Flask 的日志处理器
        for handler in app.logger.handlers:
            app.logger.removeHandler(handler)
        app.logger.addHandler(InterceptHandler())

        # 配置 Loguru
        logger.add("log/runtime_{time}.log", rotation="1024KB", enqueue=True)

        # 添加请求上下文信息
        @app.before_request
        def add_request_info():
            if has_request_context():
                logger.info(f"Request: {request.method} {request.url}")

        @app.errorhandler(Exception)
        def handle_exception(e):
            # 记录异常信息
            logger.exception(f"An error occurred: {str(e)}")

            # # 返回一个 JSON 响应
            # response = {
            #     "error": "Internal Server Error",
            #     "message": str(e)
            # }
            # return jsonify(response)

    def info(self, message, *args, **kwargs):
        logger.info(message, *args, **kwargs)

    def error(self, message, *args, **kwargs):
        logger.error(message, *args, **kwargs)

    def debug(self, message, *args, **kwargs):
        logger.debug(message, *args, **kwargs)

    def warning(self, message, *args, **kwargs):
        logger.warning(message, *args, **kwargs)
    def exception(self, message, *args, **kwargs):
        logger.critical(message)

# 自定义处理器，用于将 Flask 的日志记录转发到 Loguru
class InterceptHandler(logging.Handler):
    def emit(self, record):
        loguru_record = logger.log
        loguru_record(str(record.msg), extra={"level": record.levelname})

# 使用封装的 FlaskLogger
app = Flask(__name__)
flask_logger = FlaskLogger(app)


# @app.errorhandler(Exception)
# def handle_exception(e):
#     # 记录异常信息
#     flask_logger.exception(f"An error occurred: {str(e)}")
#
#     # 返回一个 JSON 响应
#     response = {
#         "error": "Internal Server Error",
#         "message": str(e)
#     }
#     return jsonify(response),

@app.route('/')
def index():
    a = 2/0
    print(a)
    # for i in range(10000):
    #     print(i)
    #     flask_logger.info("访问了首页" + str(i))
    return "Hello, World!"

if __name__ == '__main__':
    app.run(debug=True)